package com.jt.aop;


import com.jt.annotation.CacheFind;
import com.jt.util.ObjectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.JedisCluster;


import java.util.Arrays;


@Aspect //标识我是一个切面
@Component // 将对象交给spring容器来管理
public class CacheAOP {
    @Autowired
    private JedisCluster jedis;



    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind) {

        Object result = null;
        String key = cacheFind.key();
        String argsString = Arrays.toString(joinPoint.getArgs());
        key = key + "::" + argsString;
        try {
            if (jedis.exists(key)) {
                String json = jedis.get(key);
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                result = ObjectMapperUtil.toObject(json, methodSignature.getReturnType());
            } else {
                result = joinPoint.proceed();//执行目标方法或者是下一个方法
                String json = ObjectMapperUtil.toJson(result);
                if (cacheFind.seconds() > 0) {
                    jedis.setex(key, cacheFind.seconds(), json);
                }
                jedis.set(key, json);
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return new RuntimeException(throwable);
        }
        return result;
    }


}
